package com.clss.commandhelper.tools;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.widget.ImageView;

import com.clss.commandhelper.function.newEvidence.TaskPoliceFile;
import com.clss.commandhelper.net.ApiConstants;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by LiuV on 2017/6/23.
 */

public class UploadHelper {

	public static final int IMAGE_FROM_LOCAL = 111;
	public static final int VIDEO_FROM_LOCAL = 222;

	//指挥助手上传文件
	public static void uploadEvidenceFile(TaskPoliceFile taskPoliceFile, File file, String url, Callback callback) {
		if (file == null){
			return;
		}
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		MultipartBody body = builder.addFormDataPart("type", taskPoliceFile.getType()+"")
				.addFormDataPart("time",taskPoliceFile.getTime())
				.addFormDataPart("name",file.getName())
				.addFormDataPart("audioTime",taskPoliceFile.getAudioTime()+"")
				.addFormDataPart("address",taskPoliceFile.getAddress())
				.addFormDataPart("latlng",taskPoliceFile.getLatlng())
				.addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("application/otcet-stream"), file))
				.build();

		Request request = new Request.Builder().url(url)
				.post(body)
				.addHeader(Constant.APP_TOKEN,
						SpHelper.getInstance().getToken())
				.build();
		new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
	}



	//上传多个视频
	public static void uploadImage(File file, String url, Callback callback) {
		if (file == null) {
			return;
		}
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		MultipartBody body = builder.addFormDataPart("type", "7")
				.addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
				.build();

		Request request = new Request.Builder().url(url)
				.post(body)
				.addHeader(Constant.APP_TOKEN,
						SpHelper.getInstance().getToken())
				.build();
		new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
	}

	//上传地图截屏
	public static void uploadMapBitmap(Bitmap bitmap, Callback callback) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
		byte[] cutMap = outputStream.toByteArray();
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		MultipartBody body = builder.addFormDataPart("type", "31")
				.addFormDataPart("files", "cutMap.png", RequestBody.create(MediaType.parse("image/png"), cutMap))
				.build();

		Request request = new Request.Builder().url(ApiConstants.getUploadImageUrl())
				.post(body)
				.addHeader(Constant.APP_TOKEN,
						SpHelper.getInstance().getToken())
				.build();
		new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
	}

	/**
	 * 压缩bitmap尺寸
	 */
	public static Bitmap compressImageSizeAndLoadBitmap(String imgpath, ImageView imageView) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(imgpath, newOpts);
		newOpts.inJustDecodeBounds = false;
		int oldWidth = newOpts.outWidth;
		int oldHeight = newOpts.outHeight;
		if (newOpts.outHeight > newOpts.outWidth) {
			oldWidth = newOpts.outHeight;
			oldHeight = newOpts.outWidth;
		}
		int scale = 1;
//		if (oldWidth / imageView.getWidth() > oldHeight / imageView.getHeight()) {
//			scale = oldWidth / imageView.getWidth();
//		} else {
//			scale = oldHeight / imageView.getHeight();
//		}
		if (scale <= 0) {
			scale = 1;
		}
		newOpts.inSampleSize = scale;
		newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
		bitmap = BitmapFactory.decodeFile(imgpath, newOpts);
		return bitmap;
	}

	public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
		options.inJustDecodeBounds = false;
		Bitmap src = BitmapFactory.decodeFile(pathName, options);
		return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize);
	}

	private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// 源图片的高度和宽度
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int halfHeight = height / 2;
			final int halfWidth = width / 2;
			// Calculate the largest inSampleSize value that is a power of 2 and keeps both
			// height and width larger than the requested height and width.
			while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}
		return inSampleSize;
	}

	private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {
// 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
		Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
		if (src != dst) { // 如果没有缩放，那么不回收
			src.recycle(); // 释放Bitmap的native像素数组
		}
		return dst;
	}

	//从本地相册选择照片上传
	public static void selectImageFromStore(Activity context, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		context.startActivityForResult(intent, requestCode);
	}

	//从本地相册选择视频上传
	public static void selectVideoFromStore(Activity context, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
		context.startActivityForResult(intent, requestCode);
	}
	/**
	 * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
	 */
	public static String getImageAbsolutePath(Context context, Uri imageUri) {
		if (context == null || imageUri == null) {
			return null;
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
				DocumentsContract.isDocumentUri(context, imageUri)) {
			if (isExternalStorageDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(imageUri)) {
				String id = DocumentsContract.getDocumentId(imageUri);
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[]{split[1]};
				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(imageUri)) {
				return imageUri.getLastPathSegment();
			}
			return getDataColumn(context, imageUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			return imageUri.getPath();
		}
		return null;
	}

	public static void selectImageFromCamera(Activity context, int requestCode, File saveImage) {
		if (saveImage == null) {
			Lg.i(TAG, "Image file parameter is null.");
			saveImage = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png");
		}
		int currentapiVersion = Build.VERSION.SDK_INT;
		Lg.i(TAG, "---currentapiVersion===" + currentapiVersion);
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (currentapiVersion < Build.VERSION_CODES.N) {
			intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		} else {
			if (saveImage.exists()){
				try {
					saveImage.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ContentValues contentValues = new ContentValues();
			contentValues.put(MediaStore.Images.Media.DATA, saveImage.getAbsolutePath());
			Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		}
		context.startActivityForResult(intent, requestCode);
	}
	public static void selectVideoFromCamera(Activity context, int requestCode, File saveVideo){
		if (saveVideo == null) {
			Lg.i(TAG, "Image file parameter is null.");
			saveVideo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".mp4");
		}
		int currentapiVersion = Build.VERSION.SDK_INT;
		Lg.i(TAG, "---currentapiVersion===" + currentapiVersion);
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		if (currentapiVersion < Build.VERSION_CODES.N) {
			intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveVideo));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		} else {
			if (saveVideo.exists()){
				try {
					saveVideo.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ContentValues contentValues = new ContentValues();
			contentValues.put(MediaStore.Images.Media.DATA, saveVideo.getAbsolutePath());
			Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		}
		context.startActivityForResult(intent, requestCode);
	}


	/**
	 * 获取存储拍照图片的文件
	 */
	public static File getCameraSaveFile(Context context, long time) {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable()) {
			return new File(context.getExternalCacheDir(), time + ".png");
		} else {
			return new File(context.getCacheDir(), time + ".png");
		}
	}
	public static File getCameraSaveVideoFile(Context context, long time) {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable()) {
			return new File(context.getExternalCacheDir(), time + ".mp4");
		} else {
			return new File(context.getCacheDir(), time + ".mp4");
		}
	}

	private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = {column};
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	private static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	private static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	private static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}
}
